package com.cicadasmall.config.beetl;

import com.cicadasmall.common.func.Fn;
import com.cicadasmall.common.utils.EvnUtils;
import lombok.extern.slf4j.Slf4j;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Resource;
import org.beetl.core.ResourceLoader;
import org.beetl.core.exception.ErrorInfo;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.core.resource.FileResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.beetl.ext.spring.BeetlSpringViewResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * BeetlConfig
 *
 * @author Jin
 */
@Slf4j
@Configuration
public class BeetlConfig {

    private static final String TEMPLATES_FOLDER = "templates";

    @Bean(initMethod = "init")
    public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() {
        BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
        ResourceLoader resourceLoader;
        if (EvnUtils.isJarActive(BeetlConfig.class)) {
            //创建模板文件目录
            String templatesPath = EvnUtils.checkAndCreateResourceDir(TEMPLATES_FOLDER);
            log.info("========[ JAR方式运行设置模板路径至 - {} ]========", templatesPath);
            resourceLoader = new FileResourceLoader(templatesPath);
        } else {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            if (loader == null) {
                loader = BeetlConfig.class.getClassLoader();
            }
            resourceLoader = new ClasspathResourceLoader(loader, "templates/");
        }

        beetlGroupUtilConfiguration.setResourceLoader(resourceLoader);

        Properties properties = new Properties();
        properties.setProperty("DELIMITER_PLACEHOLDER_START", "${");
        properties.setProperty("DELIMITER_PLACEHOLDER_END", "}");
        properties.setProperty("DELIMITER_STATEMENT_START", "<!---");
        properties.setProperty("DELIMITER_STATEMENT_END", "--->");
        beetlGroupUtilConfiguration.setConfigProperties(properties);

        beetlGroupUtilConfiguration.setErrorHandler((ex, writer) -> {
            try {
                ErrorInfo err = new ErrorInfo(ex);
                String content = "<p>====================================================================================</p>" +
                        "<p style=\"font-size:14px;padding-left:10px;\"><b>" + err.getType() + "</b></p>" +
                        "<p style=\"font-size:12px;padding-left:10px;\">错误描述 : " + err.getMsg() + "</p>" +
                        "<p style=\"font-size:12px;padding-left:10px;\">错误位置 : " + Fn.list2Str(err.getResourceCallStack().stream().map(Resource::getId).collect(Collectors.toList())) + " ~ 第" + err.getErrorTokenLine() + "行</p>" +
                        "<p>====================================================================================</p>";
                writer.write(content);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        return beetlGroupUtilConfiguration;
    }


    @Bean(name = "beetlViewResolver")
    public BeetlSpringViewResolver getBeetlSpringViewResolver() {
        BeetlSpringViewResolver beetlSpringViewResolver = new BeetlSpringViewResolver();
        beetlSpringViewResolver.setContentType("text/html;charset=UTF-8");
        beetlSpringViewResolver.setOrder(0);
        beetlSpringViewResolver.setSuffix(".html");
        beetlSpringViewResolver.setConfig(getBeetlGroupUtilConfiguration());
        return beetlSpringViewResolver;
    }

    @Bean(name = "groupTemplate")
    public GroupTemplate getGroupTemplate(BeetlGroupUtilConfiguration groupUtilConfiguration) {
        return groupUtilConfiguration.getGroupTemplate();
    }

}
